<script setup>
import {ref, onMounted} from 'vue'
import axios from 'axios'
import {ElMessage} from 'element-plus'

// 筛选表单数据
const filterForm = ref({
  supplierId: null,
  partTypeId: null,
  amountAsc: null
})

// 列表数据
const partList = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 供应商列表
const supplierList = ref([])
// 零件类型列表
const partTypeList = ref([])

// 获取供应商列表
const getSupplierList = async () => {
  try {
    const response = await axios.get('/carRepair/admin/partManage/supplier')
    if (response.data.code === 200) {
      supplierList.value = response.data.data
    }
  } catch (error) {
    console.error('获取供应商列表失败:', error)
    ElMessage.error('获取供应商列表失败')
  }
}

// 获取零件类型列表
const getPartTypeList = async () => {
  try {
    const response = await axios.get('/carRepair/admin/partManage/partType')
    if (response.data.code === 200) {
      partTypeList.value = response.data.data
    }
  } catch (error) {
    console.error('获取零件类型列表失败:', error)
    ElMessage.error('获取零件类型列表失败')
  }
}

// 获取配件列表
const getPartList = async () => {
  try {
    let partTypeId = filterForm.value.partTypeId
    const response = await axios.get('/carRepair/admin/partManage', {
      params: {
        pageNum: currentPage.value,
        pageSize: pageSize.value,
        supplierId: filterForm.value.supplierId,
        partTypeId: partTypeId === null ? null : partTypeId[partTypeId.length - 1],
        amountAsc: filterForm.value.amountAsc
      }
    })
    if (response.data.code === 200) {
      partList.value = response.data.data.records
      total.value = response.data.data.total
    }
  } catch (error) {
    console.error('获取配件列表失败:', error)
    ElMessage.error('获取配件列表失败')
  }
}

// 添加到购物车
const handleAddToCart = async (part) => {
  try {
    const response = await axios.post('/carRepair/admin/partManage/partCart', {
      relationId: part.partRelationId,
      quantity: part.minOrderQuantity
    })
    if (response.data.code === 200) {
      ElMessage.success('添加成功')
    } else {
      ElMessage.error(response.data.message || '添加失败')
    }
  } catch (error) {
    console.error('添加到购物车失败:', error)
    ElMessage.error('添加到购物车失败')
  }
}

// 处理查询
const handleSearch = () => {
  currentPage.value = 1
  getPartList()
}

// 重置筛选条件
const resetFilter = () => {
  filterForm.value = {
    supplierId: null,
    partTypeId: null,
    amountAsc: null
  }
  handleSearch()
}

// 处理分页大小变化
const handleSizeChange = (val) => {
  pageSize.value = val
  getPartList()
}

// 处理页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  getPartList()
}

onMounted(() => {
  getSupplierList()
  getPartTypeList()
  getPartList()
})
</script>

<template>
  <div class="purchase">
    <!-- 条件筛选区域 -->
    <el-card class="filter-card">
      <el-form :inline="true" :model="filterForm" class="filter-form">
        <el-form-item label="供应商">
          <el-select v-model="filterForm.supplierId" placeholder="请选择供应商" clearable>
            <el-option
                v-for="item in supplierList"
                :key="item.supplierId"
                :label="item.supplierName"
                :value="item.supplierId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="零件类型">
          <el-cascader
              v-model="filterForm.partTypeId"
              :options="partTypeList"
              :props="{
              checkStrictly: true,
              value: 'typeId',
              label: 'typeName',
              children: 'childrenList'
            }"
              placeholder="请选择零件类型"
              clearable
          />
        </el-form-item>
        <el-form-item label="金额排序">
          <el-select v-model="filterForm.amountAsc" placeholder="请选择排序方式" clearable>
            <el-option label="升序" :value="true"/>
            <el-option label="降序" :value="false"/>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetFilter">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 配件列表区域 -->
    <el-card class="list-card">
      <el-table :data="partList" style="width: 100%">
        <el-table-column label="零件图片" width="120">
          <template #default="scope">
            <el-image
                style="width: 50px; height: 50px"
                :src="scope.row.imageUrl"
                :preview-src-list="[scope.row.imageUrl]"
                fit="cover"
            />
          </template>
        </el-table-column>
        <el-table-column prop="supplierName" label="供应商名称" width="150"></el-table-column>
        <el-table-column prop="partTypeName" label="零件类型名称" width="120"></el-table-column>
        <el-table-column prop="partName" label="零件名称" width="150"></el-table-column>
        <el-table-column prop="minOrderQuantity" label="最小起订量" width="120"></el-table-column>
        <el-table-column prop="supplyPrice" label="供货单价" width="120">
          <template #default="scope">
            ¥{{ scope.row.supplyPrice }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template #default="scope">
            <el-button
                type="primary"
                size="small"
                :disabled="scope.row.supplyStatus !== '正常供货'"
                @click="handleAddToCart(scope.row)"
            >
              添加到购物车
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<style scoped>
.purchase {
  padding: 0;
}

.filter-card {
  margin-bottom: 20px;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
}

.list-card {
  margin-top: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-cascader) {
  width: 150px;
}

:deep(.el-form-item) {
  margin-bottom: 0;
}
:deep(.el-table__cell) {
  padding: 1px 0;
}


:deep(.el-select) {
  width: 150px;
}
</style>